#coding=utf-8
'''
# @Name:token_itsdangerous
# @author:mysouil
# @Description:
# @DATE:2022/9/24 21:31
# @Modified By:
'''
from comment.models.user import User
from itsdangerous import TimedJSONWebSignatureSerializer
from comment.utils import const
from flask import current_app

def generate_token(user_id):
    '''
    根据已经登录之后的用户id，生成token
    :param user_id:用户id
    :return:
    '''
    
    # 参数1：密钥,参数2：token的有效时间
    s = TimedJSONWebSignatureSerializer(secret_key=const.SECRET_KEY,expires_in=const.JWT_EXPIRY_SECOND)
    
    return s.dumps({'id':user_id}).decode()


def verify_token(token_str):
    '''
    验证token，并且验证成功之后，返回用户id
    :param token_str:
    :return:
    '''

    s = TimedJSONWebSignatureSerializer(secret_key=const.SECRET_KEY)
    
    # 本质上就是一个解密的过程
    try:
        data = s.loads(token_str)
    except Exception as e:
        current_app.logger.info(e)
        return {'message':'token is invalid'}
    
    user = User.query.filter(User.id==data['id']).first()
    if user and user.status!=0:
        return {'message':'user is expired'}
    
    return {'id':user.id}
    